package com.huluobo.a2203kotlindouyindemo.home

import androidx.lifecycle.MutableLiveData
import com.huluobo.base.bean.SearchBean
import com.huluobo.base.bean.VideoBeanResult
import com.huluobo.base.db.SearchDao
import com.huluobo.base.model.BaseRepo
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 *  Created by LC on 2024/7/11.
 */
class HomeRepo : BaseRepo() {
    fun getVideoList(
        currentPage: Int,
        pageSize: Int,
        success: MutableLiveData<VideoBeanResult>,
        failed: MutableLiveData<String>
    ) {
        apiService.getVideoList(currentPage, pageSize)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<VideoBeanResult> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: VideoBeanResult) {
                    success.value = t
                }
            })
    }

    fun findVideos(keyword: String, success: MutableLiveData<VideoBeanResult>, failed: MutableLiveData<String>) {
        apiService.findVideos(keyword)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<VideoBeanResult> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: VideoBeanResult) {
                    success.value = t
                }
            })
    }

    fun saveSearch(searchBean: SearchBean) {
        db.getSearchDao().insertKeywords(searchBean)
    }

    fun querySearchKeywords(success: MutableLiveData<List<SearchBean>>, failed: MutableLiveData<String>) {
        db.getSearchDao().queryKeywords()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<List<SearchBean>> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onError(e: Throwable) {
                    failed.value = e.message
                }

                override fun onComplete() {
                }

                override fun onNext(t: List<SearchBean>) {
                    success.value = t
                }

            })
    }
}